var localDB = require('nedb');
var app = require('electron').remote;
const appPath = app.app.getPath('appData') + '\\Requester';



var formatDoc = function (doc) {
    if ((typeof doc == 'object') && doc.constructor == Object) {
        var data = doc;
        data.id = doc._id;
        // data.createdAt = doc.createdAt.getTime();
        // data.updatedAt = doc.updatedAt.getTime();
        delete data.createdAt;
        delete data.updatedAt;
        delete data.disable;
        delete data._id;
        return data;
    } else {
        return doc;
    };
};
// 格式化多行数据
var formatDocs = function (docs) {
    var _array = [];
    for (let i = 0; i < docs.length; i++) {
        const item = formatDoc(docs[i]);
        _array.push(item);
    };
    return _array;
};

var UrlDB = function (options) {
    this.db = new localDB({
        filename: appPath + '/userDB/' + options.PorjectName + '_Url' + '.db',
        autoload: true,
        timestampData: true,
    });
    this.openEvent = function () { };
    setTimeout(() => {
        this.openEvent();
    }, 10);
};
UrlDB.prototype.onOpen = function (event) {
    this.openEvent = event;
};

UrlDB.prototype.creat = function (data, cb) {
    this.db.insert({
        name: data.name,
        url: data.url,
        disable: false,
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, formatDoc(doc));
        };
    });
};

UrlDB.prototype.updata = function (id, data, cb) {
    this.db.update({ _id: id }, {
        $set: {
            name: data.name,
            url: data.url,
        }
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, doc);
        };
    });
};

UrlDB.prototype.getAll = function (cb) {
    this.db.find({ disable: false }, function (err, docs) {
        if (err) {
            cb(error, null);
        } else {
            cb(false, formatDocs(docs));
        };
    });
};

UrlDB.prototype.delete = function (id, cb) {
    this.db.update({ _id: id }, {
        $set: {
            disable: true,
        }
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, doc);
        };
    });
};



module.exports = {
    Url: function (options) {
        return new UrlDB(options);
    },
};